package com.zhiwen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiwen.common.api.PageResult;
import com.zhiwen.domain.entity.Notification;
import com.zhiwen.mapper.NotificationMapper;
import com.zhiwen.service.AnswerService;
import com.zhiwen.service.CommentService;
import com.zhiwen.service.NotificationService;
import com.zhiwen.service.NotificationTemplateService;
import com.zhiwen.service.QuestionService;
import com.zhiwen.service.NotificationProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 通知服务实现类
 */
@Slf4j
@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements NotificationService {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private NotificationTemplateService templateService;

    @Autowired
    private NotificationProducer notificationProducer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createQuestionAnsweredNotification(Long questionId, Long answerId, Long receiverId, Long senderId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendQuestionAnsweredNotification(questionId, answerId, receiverId, senderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAnswerCommentedNotification(Long answerId, Long commentId, Long receiverId, Long senderId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendAnswerCommentedNotification(answerId, commentId, receiverId, senderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAnswerAcceptedNotification(Long questionId, Long answerId, Long receiverId, Long senderId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendAnswerAcceptedNotification(questionId, answerId, receiverId, senderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createContentReviewedNotification(Integer contentType, Long contentId, Long receiverId, Integer result, String remark) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendContentReviewedNotification(contentType, contentId, receiverId, result, remark);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSystemNotification(String title, String content, Long receiverId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendSystemNotification(title, content, receiverId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createContentLikedNotification(Integer contentType, Long contentId, Long receiverId, Long senderId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendContentLikedNotification(contentType, contentId, receiverId, senderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUserFollowedNotification(Long receiverId, Long senderId) {
        // 使用异步通知生产者发送通知
        notificationProducer.sendUserFollowedNotification(receiverId, senderId);
    }

    @Override
    public Long getUnreadCount(Long userId) {
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, userId)
                .eq(Notification::getIsRead, 0);

        return count(queryWrapper);
    }

    @Override
    public PageResult<Notification> getUserNotifications(Long userId, Integer isRead, Integer pageNum, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, userId)
                .eq(isRead != null, Notification::getIsRead, isRead)
                .orderByDesc(Notification::getCreateTime);

        // 执行分页查询
        IPage<Notification> page = new Page<>(pageNum, pageSize);
        page = page(page, queryWrapper);

        // 构建分页结果
        return new PageResult<>(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsRead(Long notificationId, Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getId, notificationId)
                .eq(Notification::getReceiverId, userId);

        // 获取通知
        Notification notification = getOne(queryWrapper);
        if (notification == null) {
            return false;
        }

        // 更新为已读
        notification.setIsRead(1);
        notification.setUpdateTime(LocalDateTime.now());

        return updateById(notification);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAllAsRead(Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, userId)
                .eq(Notification::getIsRead, 0);

        // 获取所有未读通知
        List<Notification> notifications = list(queryWrapper);
        if (CollectionUtils.isEmpty(notifications)) {
            return true;
        }

        // 批量更新为已读
        for (Notification notification : notifications) {
            notification.setIsRead(1);
            notification.setUpdateTime(LocalDateTime.now());
        }

        return updateBatchById(notifications);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteNotification(Long notificationId, Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getId, notificationId)
                .eq(Notification::getReceiverId, userId);

        return remove(queryWrapper);
    }

    /**
     * 创建通知实体
     *
     * @param receiverId 接收者ID
     * @param senderId 发送者ID
     * @param type 通知类型
     * @param relatedId 关联ID
     * @param title 标题
     * @param content 内容
     * @param linkUrl 链接URL（使用content字段的后半部分存储）
     * @return 通知实体
     */
    private Notification createNotificationEntity(Long receiverId, Long senderId, Integer type, Long relatedId, String title, String content, String linkUrl) {
        Notification notification = new Notification();
        notification.setReceiverId(receiverId);
        notification.setSenderId(senderId);
        notification.setType(type);
        notification.setRelatedId(relatedId);
        notification.setTitle(title);
        notification.setContent(content + "|LINK|" + linkUrl); // 将链接URL嵌入到内容字段中
        notification.setIsRead(0);
        notification.setCreateTime(LocalDateTime.now());
        notification.setUpdateTime(LocalDateTime.now());
        notification.setDeleted(0);

        return notification;
    }
}
